package com.blog.controller;

import com.blog.exception.ExceptionEnum;
import com.blog.exception.MyException;
import com.blog.pojo.ResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.regex.Pattern;

import static com.blog.utils.EmailSendUtils.sendMessage;


@RestController
@RequestMapping("/email")
@Slf4j
public class EmailController {

    @GetMapping
    public ResultResponse getCode(@RequestParam("email")String email){
        if ((email == null) || (email.isEmpty())) {
            throw new MyException(ExceptionEnum.EMPTY_EMAIL);
        }
        if(!Pattern.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$", email)){
            throw new MyException(ExceptionEnum.ERROR_EMAIL_FORMAT);
        }

        try{
            String verificationCode = sendMessage(email);
            return ResultResponse.success(verificationCode);
        }catch(Exception e){
            throw new RuntimeException("邮件发送失败！"+e);
        }
    }
}